'use client';

import React, { useState, useEffect } from 'react';

interface CalendarProps {
  onDateSelect: (date: string) => void;
  bookedDates: string[];
}

const Calendar: React.FC<CalendarProps> = ({ onDateSelect, bookedDates }) => {
  const [currentMonth, setCurrentMonth] = useState<Date>(new Date());
  const [dates, setDates] = useState<Date[]>([]);

  // 生成当月日期数组
  useEffect(() => {
    const year = currentMonth.getFullYear();
    const month = currentMonth.getMonth();
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    const daysInMonth = lastDay.getDate();
    const startDayOfWeek = firstDay.getDay(); // 0-6, 0为星期日

    const dateArray: Date[] = [];

    // 添加上个月的末尾日期以填充日历第一行
    for (let i = startDayOfWeek - 1; i >= 0; i--) {
      const prevDate = new Date(year, month, -i);
      dateArray.push(prevDate);
    }

    // 添加当月的所有日期
    for (let i = 1; i <= daysInMonth; i++) {
      dateArray.push(new Date(year, month, i));
    }

    setDates(dateArray);
  }, [currentMonth]);

  // 检查日期是否可预约（从当天开始的未来日期）
  const isBookableDate = (date: Date): boolean => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    date.setHours(0, 0, 0, 0);
    return date >= today;
  };

  // 检查日期是否已被预约
  const isDateBooked = (date: Date): boolean => {
    const dateStr = date.toISOString().split('T')[0];
    return bookedDates.includes(dateStr);
  };

  // 格式化日期为YYYY-MM-DD字符串
  const formatDate = (date: Date): string => {
    return date.toISOString().split('T')[0];
  };

  // 切换到上个月
  const goToPreviousMonth = () => {
    setCurrentMonth(new Date(currentMonth.getFullYear(), currentMonth.getMonth() - 1));
  };

  // 切换到下个月
  const goToNextMonth = () => {
    setCurrentMonth(new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1));
  };

  // 格式化月份显示
  const formatMonthYear = (): string => {
    const options: Intl.DateTimeFormatOptions = { year: 'numeric', month: 'long' };
    return currentMonth.toLocaleDateString('zh-CN', options);
  };

  return (
    <div className="calendar-container bg-white p-6 rounded-xl shadow-lg">
      {/* 月份导航 */}
      <div className="flex justify-between items-center mb-8">
        <button 
          onClick={goToPreviousMonth} 
          className="p-2 bg-teal-50 hover:bg-teal-100 text-teal-700 rounded-lg transition-colors duration-200"
          aria-label="上个月"
        >
          <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
          </svg>
        </button>
        <h3 className="text-2xl font-bold text-teal-700">{formatMonthYear()}</h3>
        <button 
          onClick={goToNextMonth} 
          className="p-2 bg-teal-50 hover:bg-teal-100 text-teal-700 rounded-lg transition-colors duration-200"
          aria-label="下个月"
        >
          <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
          </svg>
        </button>
      </div>

      {/* 星期标题 */}
      <div className="grid grid-cols-7 gap-2 mb-4">
        {['日', '一', '二', '三', '四', '五', '六'].map((day, index) => (
          <div key={index} className="text-center font-medium text-gray-600 py-3">
            {day}
          </div>
        ))}
      </div>

      {/* 日期网格 */}
      <div className="grid grid-cols-7 gap-2">
        {dates.map((date, index) => {
          const isCurrentMonth = date.getMonth() === currentMonth.getMonth();
          const isToday = date.toDateString() === new Date().toDateString();
          const bookable = isBookableDate(date);
          const booked = isDateBooked(date);

          return (
            <button
              key={index}
              className={`
                aspect-square rounded-lg flex flex-col items-center justify-center transition-all duration-300 transform
                ${!isCurrentMonth ? 'text-gray-300 opacity-50' : ''}
                ${isToday ? 'bg-teal-100 border-2 border-teal-500 font-bold text-teal-800' : ''}
                ${!bookable ? 'text-gray-400 cursor-not-allowed' : ''}
                ${bookable && booked ? 'bg-red-100 text-red-700 hover:bg-red-200' : ''}
                ${bookable && !booked ? 'bg-white hover:bg-blue-50 hover:scale-[1.05] cursor-pointer shadow-sm text-gray-800' : ''}
              `}
              onClick={() => bookable && onDateSelect(formatDate(date))}
              disabled={!bookable}
            >
              <span className="text-base font-medium">{date.getDate()}</span>
              {booked && (
                <span className="mt-1 text-xs text-red-600">已预约</span>
              )}
              {isToday && !booked && (
                <span className="mt-1 text-xs text-teal-600">今天</span>
              )}
            </button>
          );
        })}
      </div>
    </div>
  );
};

export default Calendar;